package com.factory.rest.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.factory.common.bean.CloudRadio;
import com.factory.common.bean.Config;
import com.factory.common.bean.User;
import com.factory.common.core.BaseService;
import com.factory.common.core.ValidateType;
import com.factory.common.pojo.Result;
import com.factory.common.pojo.SendData;
import com.factory.common.utils.DateUtil;
import com.factory.common.utils.FileUtils;
import com.factory.common.utils.StringUtil;
import com.factory.rest.feign.AiClients;
import com.factory.rest.pojo.CloudRadioPojo;
import com.factory.rest.service.CloudRadioService;
import com.factory.rest.service.ConfigService;
import com.factory.rest.service.UserDevicesService;
import com.factory.rest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 云广播控制器
 *
 * @author JW
 * @version 1.0
 * @date 2021/5/18 15:55
 */
@RestController
@RequestMapping("/rest/cloudRadio")
public class CloudRadioController extends BaseController<CloudRadioPojo>{

    @Autowired
    private CloudRadioService cloudRadioService;

    @Autowired
    private UserService userService;

    @Autowired
    private AiClients aiClients;

    @Autowired
    private UserDevicesService userDevicesService;

    @Autowired
    private ConfigService configService;

    @Value("${jiexun.upload.dir}")
    private String uploadDir;

    @Override
    protected BaseService getBaseService() {
        return cloudRadioService;
    }


    @Override
    public Result insert(@RequestBody CloudRadioPojo cloudRadioPojo) {

        //校验
        Optional<Result> validate = cloudRadioPojo.validate(ValidateType.INSERT);
        if (validate.isPresent()) {
            return validate.get();
        }

        User user = userService.getLoginUser().get();
        cloudRadioPojo.setUserId(user.getId());
        cloudRadioPojo.setUserName(user.getName());

        String path = cloudRadioPojo.getPath();
        if(StringUtil.notEmpty(path)){
            String filePath =  "radio" + File.separator + DateUtil.getDateString(new Date(), "yyyy-MM-dd");
            String fileName = FileUtils.move(uploadDir + File.separator + path, uploadDir + File.separator + filePath);

            if(null != fileName){
                cloudRadioPojo.setPath(filePath + File.separator + fileName);
                cloudRadioPojo.setType(path.substring(path.lastIndexOf(".") + 1));
            }
            else
                cloudRadioPojo.setPath(null);
        }

        return Result.success(cloudRadioService.insert(cloudRadioPojo));
    }


    @Override
    public Result update(@RequestBody CloudRadioPojo cloudRadioPojo) {
        //校验
        Optional<Result> validate = cloudRadioPojo.validate(ValidateType.UPDATE);
        if (validate.isPresent()) {
            return validate.get();
        }

        String path = cloudRadioPojo.getPath();
        if(StringUtil.notEmpty(path)){
            String filePath =  DateUtil.getDateString(new Date(), "yyyy-MM-dd");
            String fileName = FileUtils.move(uploadDir + File.separator + path, uploadDir + File.separator + filePath);

            if(null != fileName){
                cloudRadioPojo.setPath(filePath + File.separator + fileName);
                cloudRadioPojo.setType(path.substring(path.lastIndexOf(".") + 1));
            }
            else
                cloudRadioPojo.setPath(null);
        }

        return Result.success(cloudRadioService.updateById(cloudRadioPojo));
    }

    /**
     * 播放
     * @param params
     * @return
     */
    @PostMapping("/play")
    public Result play(@RequestBody Map<String, Object> params) {

        if(StringUtil.isEmpty(params.get("devices"))){
            return Result.fail("设备id列表不能为空");
        }else if(StringUtil.isEmpty(params.get("radios"))){
            return Result.fail("播放列表不能为空");
        }

        List<CloudRadio> cloudRadios = cloudRadioService.selectList(new QueryWrapper<CloudRadio>().in("id", (List<String>)params.get("radios")).orderByAsc("number"));
        if(cloudRadios.isEmpty()){
            return Result.fail("播放列表不能为空!");
        }
        String uri = "https://www.2edge.cn/rest/index/download/";
        cloudRadios = cloudRadios.stream().map(e -> {
            if(null != e.getPath())
                e.setPath(uri + Base64.getUrlEncoder().encodeToString(e.getPath().getBytes()));
            return e;
        }).collect(Collectors.toList());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("play_list",cloudRadios);
        jsonObject.put("type", 1);
        jsonObject.put("volume", 100);
        //修改配置
        User user = userService.getLoginUser().get();
        List<Config> configList = configService.selectList(new QueryWrapper<Config>().eq("user_id", user.getId()));
        configList.forEach(e -> {
            if("cloud_radio_type".equals(e.getCkey()))
                jsonObject.put("type", StringUtil.toInteger(e.getCvalue(),1));
            else if("cloud_radio_volume".equals(e.getCkey()))
                jsonObject.put("volume", StringUtil.toInteger(e.getCvalue(),100));
        });

        ((List<String>) params.get("devices")).forEach(device -> {
            //发送到客户端
            aiClients.sendClient(new SendData(device, StringUtil.getUUID(), "start_radios", jsonObject, false));
        });

        return Result.success("成功!");
    }

    /**
     * 播放
     * @param params
     * @return
     */
    @PostMapping("/stop")
    public Result stop(@RequestBody Map<String, Object> params) {

        if(StringUtil.isEmpty(params.get("devices"))){
            return Result.fail("设备id列表不能为空");
        }

        //发送到客户端
        JSONObject jsonObject = new JSONObject();

        ((List<String>) params.get("devices")).forEach(device -> {
            //发送到客户端
            aiClients.sendClient(new SendData(device, StringUtil.getUUID(), "stop_radios", jsonObject, false));
        });

        return Result.success("成功!");
    }
}
